package com.yjhb.android.sbz.activity;

import android.content.Intent;
import android.view.Gravity;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioGroup;
import android.widget.TextView;

import androidx.appcompat.widget.AppCompatRadioButton;

import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.view.TimePickerView;
import com.yjhb.android.sbz.App;
import com.yjhb.android.sbz.R;
import com.yjhb.android.sbz.dialog.LoopDialog;
import com.yjhb.android.sbz.entity.Timer;
import com.yjhb.android.sbz.manager.ResManager;
import com.yjhb.android.sbz.mvp.settingtimer.SettingTimerPresenter;
import com.yjhb.android.sbz.mvp.settingtimer.SettingTimerView;
import com.yjhb.android.sbz.tool.EventMsg;
import com.jojo.android.zxlib.tool.ZxLogTool;
import com.jojo.android.zxlib.tool.ZxTimeTool;
import com.jojo.android.zxlib.tool.ZxToast;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 创建者 zx
 * 创建时间 2021/1/12 16:15
 */
public class SettingAutoRefreshTimerActivity extends BaseActivity<SettingTimerPresenter> implements SettingTimerView {
    private final String TAG = "SettingTimerActivity";
    @BindView(R.id.back)
    FrameLayout back;
    @BindView(R.id.title_tv)
    TextView titleTv;
    @BindView(R.id.topTime_tv)
    TextView topTimeTv;
    @BindView(R.id.topTime_more_iv)
    ImageView topTimeMoreIv;
    @BindView(R.id.ll_topTime)
    LinearLayout llTopTime;
    @BindView(R.id.endTime_tv)
    TextView endTimeTv;
    @BindView(R.id.endTime_more_iv)
    ImageView endTimeMoreIv;
    @BindView(R.id.recommend_ll)
    LinearLayout recommendLl;
    @BindView(R.id.rate_tv)
    TextView rateTv;
    @BindView(R.id.rate_more_iv)
    ImageView rateMoreIv;
    @BindView(R.id.refresh_frequency_ll)
    LinearLayout refreshFrequencyLl;
    @BindView(R.id.radio_1)
    AppCompatRadioButton radio1;
    @BindView(R.id.radio_2)
    AppCompatRadioButton radio2;
    @BindView(R.id.rg_repeat)
    RadioGroup rgRepeat;
    @BindView(R.id.refresh_count_tv)
    TextView refreshCountTv;
    @BindView(R.id.buy_refresh)
    TextView buyRefresh;
    @BindView(R.id.addTimer_tv)
    TextView addTimerTv;


    private Date startTime;
    private Date endTime;
    private int rate; //频率 单位分钟
    private Integer taskId;
    private Timer timer;
    private List<Timer> timerList;

    @Override
    protected SettingTimerPresenter initPresenter() {
        return new SettingTimerPresenter(this);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_setting_auto_refresh_timer;
    }

    @Override
    protected void initUI() {
        taskId = getIntent().getIntExtra("taskId", -1);
        if (taskId == -1) {
            ZxToast.showINFOBottomToast("任务ID异常，请联系管理员。");
            finish();
        }
        timer = (Timer) getIntent().getSerializableExtra("timer");
        timerList = (ArrayList<Timer>) getIntent().getSerializableExtra("timerList");

    }

    @Override
    protected void initData() {
        try {
            if (timer != null) {
                startTime = ZxTimeTool.string2Date(timer.getStartDay() + " " + timer.getStartTime());
                endTime = ZxTimeTool.string2Date(timer.getEndDay() + " " + timer.getEndTime());
                rate = timer.getRate();
                topTimeTv.setText(ZxTimeTool.getDate(startTime.getTime(), "HH时mm分"));
                endTimeTv.setText(ZxTimeTool.getDate(endTime.getTime(), "HH时mm分"));
                rateTv.setText(getRateName(rate));
                rgRepeat.clearCheck();
                rgRepeat.check(timer.getIsLoop() == 1 ? R.id.radio_1 : R.id.radio_2);

            }
        } catch (Exception e) {
            ZxLogTool.err(e);
        }

    }

    @Override
    protected void regEvent() {

    }


    @Override
    public void refresh() {
        super.refresh();
        refreshCountTv.setText("购买刷新:  " + App.userInfo.getPayFlushCount() + "次");
        if (timer != null) {
            switch (timer.getState()) {
                case 0:
                    addTimerTv.setText("停止(运行中)");
                    break;
                case 1:
                    addTimerTv.setText("开始");
                    break;
                default:
                    addTimerTv.setText("不可用");
            }
        } else {
            addTimerTv.setText("开始");
        }
    }

    @OnClick(R.id.back)
    void back() {
        finish();
    }

    @OnClick({R.id.topTime_tv, R.id.topTime_more_iv})
    void topTime() {
        TimePickerView pvTime = new TimePickerBuilder(this, (date, v) -> {
            this.startTime = date;
            topTimeTv.setText(ZxTimeTool.getDate(startTime.getTime(), "HH时mm分"));
        })
                .setType(new boolean[]{false, false, false, true, true, false})// 默认全部显示
                .setCancelColor(ResManager.getThemeColor())
                .setSubmitColor(ResManager.getThemeColor())
                .setRangDate(Calendar.getInstance(), null)
                .isCyclic(false)
                .build();
        if (startTime != null) {
            Calendar time = Calendar.getInstance();
            time.setTime(this.startTime);
            pvTime.setDate(time);
        }
        pvTime.show();
    }

    @OnClick({R.id.endTime_tv, R.id.endTime_more_iv})
    void endTime() {
        if (startTime == null) {
            ZxToast.showBottomToast("请先选择开始时间");
            return;
        }
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(startTime);
        TimePickerView pvTime = new TimePickerBuilder(this, (date, v) -> {

            if (timerList != null) {
                for (Timer t : timerList) {
                    String startTimeStr = ZxTimeTool.getDate(startTime.getTime(), "HH:mm:00");
                    String endTimeStr = ZxTimeTool.getDate(date.getTime(), "HH:mm:00");
                    if (startTimeStr.equals(t.getStartTime()) && endTimeStr.equals(t.getEndTime())) {
                        ZxToast.showBottomToastLight("您已发布过该时间段的定时刷新！");
                        return;
                    }
                }
            }

            this.endTime = date;
            endTimeTv.setText(ZxTimeTool.getDate(endTime.getTime(), "HH时mm分"));
        })
                .setType(new boolean[]{false, false, false, true, true, false})// 默认全部显示
                .setCancelColor(ResManager.getThemeColor())
                .setSubmitColor(ResManager.getThemeColor())
                .setRangDate(calendar, null)
                .isCyclic(false)
                .build();
        if (endTime != null) {
            Calendar time = Calendar.getInstance();
            time.setTime(this.endTime);
            pvTime.setDate(time);
        }
        pvTime.show();
    }

    @OnClick({R.id.rate_tv, R.id.rate_more_iv})
    void rate() {
        LoopDialog loopDialog = new LoopDialog(this);
        loopDialog.setOnSelectedListener(new LoopDialog.OnSelectedListener() {
            @Override
            public void onSelected(LoopDialog.LoopItem item) {
                rateTv.setText(item.itemName);
                rate = (Integer) item.data;
            }
        });
        List<LoopDialog.LoopItem> data = new ArrayList<>();
        data.add(new LoopDialog.LoopItem(1, getRateName(1)));
        data.add(new LoopDialog.LoopItem(5, getRateName(5)));
        data.add(new LoopDialog.LoopItem(10, getRateName(10)));
        data.add(new LoopDialog.LoopItem(60, getRateName(60)));
        data.add(new LoopDialog.LoopItem(60 * 2, getRateName(60 * 2)));
        data.add(new LoopDialog.LoopItem(60 * 4, getRateName(60 * 4)));
        loopDialog.getTitleView().setText("选择刷新频率");
        loopDialog.getTitleView().setGravity(Gravity.CENTER_HORIZONTAL | Gravity.TOP);
        loopDialog.show(data);
    }

    private String getRateName(int rate) {
        switch (rate) {
            case 1:
                return "1分钟";
            case 5:
                return "5分钟";
            case 10:
                return "10分钟";
            case 60:
                return "1小时";
            case 120:
                return "2小时";
            case 240:
                return "4小时";
            default:
                return "";
        }
    }


    @OnClick(R.id.addTimer_tv)
    void addTimer_tv() {
        if (timer != null) {
            switch (timer.getState()) {
                case 0:
                    addTimer(2);
                    break;
                case 1:
                    addTimer(1);
                    break;
            }
        } else {
            addTimer(0);
        }

    }

    /**
     * @param type 0开始计时器  1更新计时器 2停止计时器
     */
    private void addTimer(int type) {
        Timer timer = new Timer();
        if (startTime == null) {
            ZxToast.showINFOBottomToast("请选择刷新开始的时间哦~~");
            return;
        }
        if (endTime == null) {
            ZxToast.showINFOBottomToast("请选择刷新结束的时间哦~~");
            return;
        }
        if (rate < 1) {
            ZxToast.showINFOBottomToast("请选择刷新频率哦~~");
            return;
        }

        //开始时间
        timer.setStartDay(ZxTimeTool.getDate(startTime.getTime(), "yyyy-MM-dd 00:00:00"));
        timer.setStartTime(ZxTimeTool.getDate(startTime.getTime(), "yyyy-MM-dd HH:mm:00"));
        //结束时间
        timer.setEndDay(ZxTimeTool.getDate(endTime.getTime(), "yyyy-MM-dd 00:00:00"));
        timer.setEndTime(ZxTimeTool.getDate(endTime.getTime(), "yyyy-MM-dd HH:mm:00"));
        //是否循环
        timer.setIsLoop(rgRepeat.getCheckedRadioButtonId() == R.id.radio_1 ? 1 : 0);
        //刷新频率
        timer.setRate(rate);
        timer.setTaskId(taskId);
        timer.setUserId(Integer.parseInt(App.userInfo.getId()));
        timer.setType(2);
        if (type == 0) {
            presenter.addTimer(timer);
        } else if (type == 1) {
            timer.setId(this.timer.getId());
            timer.setState(0);
            presenter.updateTimer(timer);
        } else if (type == 2) {
            presenter.changeState(this.timer.getId(), 1);
        }

    }


    @OnClick(R.id.buy_refresh)
    public void buy_refresh() {
        startActivity(new Intent(this, RefreshPackageActivity.class));
    }

    @Override
    public void onEventMsg(EventMsg msg) {
        super.onEventMsg(msg);
        if (msg.msg == EventMsg.USER_UPDATE_OK) {
            refresh();
        }
    }

    @Override
    public void onWait(String tips) {
        loadingDialog.setTipsText(tips);
        loadingDialog.show();
    }

    @Override
    public void onSuccess(int type, Object o) {
        loadingDialog.cancel();
        EventBus.getDefault().post(new EventMsg(EventMsg.REQUEST_REFRESH_TIMER_LIST, null));
        if (type == 0 || type == 1) {
            setResult(RESULT_OK);
            finish();
        } else {
            timer.setState(1);
            refresh();
        }
    }

    @Override
    public void onFailure(int code, String msg) {
        loadingDialog.cancel();
        ZxToast.showINFOBottomToast(msg);
    }


}
